package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.RoleMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.UserRoleMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Role;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.UserRole;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<Role> getRoleList() {
        try {
            LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Role::getStatus, 1); // 只查询启用的角色
            wrapper.orderByAsc(Role::getId);
            return roleMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("获取角色列表失败", e);
            return List.of();
        }
    }

    @Override
    @Transactional
    public boolean createRole(Role role) {
        try {
            if (role == null || role.getRoleName() == null || role.getRoleCode() == null) {
                throw new IllegalArgumentException("角色名称和角色代码不能为空");
            }

            // 检查角色代码是否已存在
            LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Role::getRoleCode, role.getRoleCode());
            Long count = roleMapper.selectCount(wrapper);
            if (count > 0) {
                throw new IllegalArgumentException("角色代码已存在");
            }

            // 设置默认值
            if (role.getStatus() == null) {
                role.setStatus(1); // 默认启用
            }
            if (role.getPermissions() == null) {
                role.setPermissions("[]"); // 默认空权限列表
            }

            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());

            int result = roleMapper.insert(role);
            return result > 0;
        } catch (Exception e) {
            log.error("创建角色失败", e);
            throw e;
        }
    }

    @Override
    @Transactional
    public boolean assignRoleToUser(Long userId, Long roleId) {
        try {
            if (userId == null || roleId == null) {
                throw new IllegalArgumentException("用户ID和角色ID不能为空");
            }

            // 检查角色是否存在
            Role role = roleMapper.selectById(roleId);
            if (role == null) {
                throw new IllegalArgumentException("角色不存在");
            }

            // 检查是否已经分配
            LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserRole::getUserId, userId);
            wrapper.eq(UserRole::getRoleId, roleId);
            Long count = userRoleMapper.selectCount(wrapper);
            if (count > 0) {
                throw new IllegalArgumentException("该角色已分配给用户");
            }

            // 创建用户角色关联
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setUpdateTime(LocalDateTime.now());

            int result = userRoleMapper.insert(userRole);
            return result > 0;
        } catch (Exception e) {
            log.error("分配角色失败", e);
            throw e;
        }
    }

    @Override
    public List<Role> getUserRoles(Long userId) {
        try {
            if (userId == null) {
                return List.of();
            }

            // 查询用户角色关联
            LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserRole::getUserId, userId);
            List<UserRole> userRoles = userRoleMapper.selectList(wrapper);

            // 获取角色列表
            List<Long> roleIds = userRoles.stream()
                    .map(UserRole::getRoleId)
                    .collect(Collectors.toList());

            if (roleIds.isEmpty()) {
                return List.of();
            }

            LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
            roleWrapper.in(Role::getId, roleIds);
            roleWrapper.eq(Role::getStatus, 1);
            return roleMapper.selectList(roleWrapper);
        } catch (Exception e) {
            log.error("获取用户角色失败", e);
            return List.of();
        }
    }
}

